import { ref, reactive, onMounted, } from "vue";
import { useRoute } from "vue-router";
import qs from "qs";
import { ElMessage } from "element-plus";
import {
  GetExamineApproveProjectName,
  GetCreditEnhancement,
  GetAllByAssetTransferId,
  GetSPVName,
  SecurityCreditRatingGetInfo,
  PredeterminedRating,
  SecurityCreditRatingApprove,
  GetPassAuditProjectName,
  FinancialTransactionsUsersGetByUsername,
  GetStockExchangeName,
  GetSettlementTime,
  GetInfoByAssetTransferId
} from "@/api/stu/SupplyChainFinance";
import { nextTick } from "process";
import { cloneDeep } from "@pureadmin/utils";
export function usePortrait() {
  const route = useRoute()
  const filterDataList = ref([])
  const isApprove = ref(false) //审批状态
  const announcementDialog = ref(false)
  const approveDialog = ref(false)
  const showReport = ref<boolean>(false);
  const informationDialog = ref<boolean>(false);
  const isShowSave = ref<boolean>(false);
  const selectItem = ref()
  const filterSelectId = ref('')
  const selectName = ref()
  const selectAssetPoolId = ref()
  const selectSecurityCreditRatingId = ref()
  const projectpProposalsData = ref() //出具项目方案数据
  const reportData = ref()
  const allNeedDay = reactive({
    gradeStrong: '',
    spvName: '', resultStr: '',
    stockExchangeName: ''
  })

  const dataList = ref([])
  const declareList = ref([
    {
      name: '资料准备',
      status: '0',
    },
    {
      name: '项目初步评估',
      status: '0',
    },
    {
      name: '出具项目方案',
      status: '0',
    },
    {
      name: '尽职调查',
      status: '0',
    },
    {
      name: '挂牌转让申请书',
      status: '0',
    },
    {
      name: '计划说明书',
      status: '0',
    },
    {
      name: '法律意见书',
      status: '0',
    },
    {
      name: '信用评级报告',
      status: '0',
    }, {
      name: '主要交易合同文本',
      status: '0',
    },
    {
      name: '其他中介报告',
      status: '0',
    },
    {
      name: '其他资料',
      status: '0',
    },
  ])
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "项目名称",
      prop: "assetSecuritizationName",
      minWidth: 150
    }, {
      label: "审批状态",
      prop: "isApprove",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.isApprove ? "success" : "error"}>
          {
            row.isApprove ? "已审批" : "待审批"
          }
        </el-tag>
      )
    }, {
      label: "操作",
      fixed: "right",
      width: 160,
      slot: "operation"
    }
  ]

  const columns1: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "项目名称",
      prop: "assetSecuritizationName",
      minWidth: 150
    }, {
      label: "操作",
      fixed: "right",
      width: 160,
      slot: "operation"
    }
  ]

  const reportList = ref([])
  const announcementData = reactive({
    year: '',
    month: '',
    day: '',
    name: '',
    tittle: ''
  })
  onMounted(async () => {
    getList()
    const params = qs.stringify({
      userName: '证券承销商',
      taskId: route.query.taskId,
      planId: route.query.planId,
    })
    let res1 = await FinancialTransactionsUsersGetByUsername(params)
  })

  async function getList() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    const res = await GetExamineApproveProjectName(data)
    if (res.success) {
      dataList.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
    const data1 = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    const res1 = await GetPassAuditProjectName(data1)
    if (res1.success) {
      reportList.value = res1.data
      // reportList.value.forEach(item => item.tittle = item.assetSecuritizationName + '在上海证券交易所挂牌转让的公告')
    } else {
      ElMessage.error(res1.msg)
    }
  }
  async function showInformation(item) {
    isShowSave.value = false
    if (item.status == 1) {
      isShowSave.value = true
    }
    selectItem.value = item
    if (item.name == '出具项目方案') {
      const data1 = qs.stringify({
        assetTransferId: filterSelectId.value
      })
      let res1 = await GetInfoByAssetTransferId(data1)
      if (res1.success) {
        projectpProposalsData.value = res1.data
      } else {
        ElMessage.error(res1.msg)
      }
      const data = qs.stringify({
        assetTransferId: filterSelectId.value,
        taskId: route.query.taskId,
        planId: route.query.planId,
      })
      let res = await GetCreditEnhancement(data)
      if (res.success) {
        allNeedDay.gradeStrong = res.data.map(item =>
          item.creditEnhancementName
        ).join(',')
      } else {
        ElMessage.error(res.msg)
      }
    }
    if (item.name == '挂牌转让申请书') {
      const data1 = qs.stringify({
        assetTransferId: filterSelectId.value
      })
      let res4 = await GetSPVName(data1)
      if (res4.success) {
        allNeedDay.spvName = res4.data.spvCompanyName
      } else {
        ElMessage.warning(res4.msg)
      }
    }
    if (item.name == '信用评级报告') {
      const data1 = qs.stringify({
        securityCreditRatingId: selectSecurityCreditRatingId.value
      })
      let res4 = await SecurityCreditRatingGetInfo(data1)
      if (res4.success) {
        res4.data.creditEnhancementRanking = JSON.parse(res4.data.creditEnhancementRanking)
        const item = res4.data
        let res = await PredeterminedRating(data1)
        const gradeArr = ['A', 'AA', 'AAA', 'B', 'BB', 'BBB', 'C', 'CC', 'CCC']
        for (var i = 0; i < item.creditEnhancementRanking.length; i++) {
          const index = gradeArr.findIndex(a => a == res.data)// 根据索引获取对应的等级
          const resultIndex = index + i
          item.creditEnhancementRanking[i].preGrade = gradeArr[resultIndex]
          console.log(item.creditEnhancementRanking[i]);
        }
        var result = "";
        for (var i = 0; i < item.creditEnhancementRanking.length; i++) {
          result += `${item.creditEnhancementRanking[i].priorityName}资产支持证券的信用等级为${item.creditEnhancementRanking[i].preGrade};`;
        }
        allNeedDay.resultStr = result
        reportData.value = item
      } else {
        ElMessage.warning(res4.msg)
      }
    }
    informationDialog.value = true
  }

  async function showInformationDetail(item) {
    if (item.isApprove == true) {
      isApprove.value = true
    } else {
      isApprove.value = false
    }
    selectName.value = item.assetSecuritizationName
    selectAssetPoolId.value = item.assetPoolId
    const data2 = qs.stringify({
      id: selectAssetPoolId.value
    })
    let res5 = await GetStockExchangeName(data2)
    if (res5.success) {
      allNeedDay.stockExchangeName = res5.data
    } else {
      ElMessage.warning(res5.msg)
    }
    selectSecurityCreditRatingId.value = item.securityCreditRatingId
    filterSelectId.value = item.assetTransferId
    approveDialog.value = true
  }

  async function saveApprove() {
    //获取转账id
    const params = qs.stringify({
      userName: '证券承销商',
      taskId: route.query.taskId,
      planId: route.query.planId,
    })
    let res1 = await FinancialTransactionsUsersGetByUsername(params)
    const fromTransactionsUserId = res1.data.transactionsUserId
    const data = qs.stringify({
      securityCreditRatingId: selectSecurityCreditRatingId.value,
      fromTransactionsUserId: fromTransactionsUserId,
      assetSecuritizationName: selectName.value,
    })
    let res = await SecurityCreditRatingApprove(data)
    if (res.success) {
      ElMessage.success(res.msg)
      getList()
      approveDialog.value = false
    } else {
      ElMessage.error(res.msg)
    }
  }

  async function showReportDetail(item) {
    selectAssetPoolId.value = item.assetPoolId
    const data2 = qs.stringify({
      id: selectAssetPoolId.value
    })
    let res5 = await GetStockExchangeName(data2)
    if (res5.success) {
      allNeedDay.stockExchangeName = res5.data
    } else {
      ElMessage.warning(res5.msg)
    }
    selectSecurityCreditRatingId.value = item.securityCreditRatingId
    filterSelectId.value = item.assetTransferId
    announcementData.name = item.assetSecuritizationName
    announcementData.tittle = item.assetSecuritizationName + `在${allNeedDay.stockExchangeName}挂牌转让的公告`
    let resStartData = await GetSettlementTime(qs.stringify({
      assetPoolId: selectAssetPoolId.value
    }))
    if (resStartData.success) {
      const dateArr = resStartData.data.substring(0, 10).split("-");
      announcementData.year = dateArr[0];
      announcementData.month = dateArr[1]
      announcementData.day = dateArr[2]
      announcementDialog.value = true
    } else {
      ElMessage.warning(resStartData.msg)
    }
  }
  return {
    showReport,
    filterSelectId,
    dataList,
    informationDialog,
    showInformation,
    selectItem,
    declareList,
    isShowSave,
    filterDataList,
    projectpProposalsData,
    allNeedDay,
    selectName,
    reportData,
    showInformationDetail,
    isApprove,
    approveDialog,
    saveApprove,
    reportList,
    showReportDetail,
    announcementData,
    announcementDialog,
    columns, columns1
  }
}